class UpgradeToSourdough < ActiveRecord::Migration
  def self.up
    ActiveRecord::Base.transaction do

      create_table "roles" do |t|
        t.column "title", :string
      end

      create_table "roles_users", :id => false do |t|
        t.column "role_id", :integer
        t.column "user_id", :integer
      end

      add_column :users, :time_zone, :string, :default => 'Pacific Time (US & Canada)'
      add_column :users, :activation_code, :string, :limit => 40
      add_column :users, :activated_at, :datetime
      add_column :users, :visits_count, :integer, :default => 0
      add_column :users, :last_login_at, :datetime
      add_column :photos, :user_id, :integer

      foreign_key :roles_users, :role_id, :roles
      foreign_key :roles_users, :user_id, :users

      User.update_all "time_zone = 'US/Pacific'"
      User.update_all "activated_at = NOW()"

      User.find(:all).each do |user|
        photo = Photo.find_by_id(user.photo_id)
        if photo
          photo.user = user
          photo.save
        end
      end

      Role.create(:title => 'admin')
      role = Role.find_by_title('admin')
      chris = User.find_by_login('chrisblanchard')
      if chris
        chris.roles << role
        chris.save!
      end
      wyatt = User.find_by_login('wyattwerner')
      if wyatt
        wyatt.roles << role
        wyatt.save!
      end
      opensourcery = User.find_by_login('opensourcery')
      if opensourcery
        opensourcery.roles << role
        opensourcery.save!
      end
    end
  end

  def self.down
    ActiveRecord::Base.transaction do
      remove_column :users, :time_zone
      remove_column :users, :activation_code
      remove_column :users, :activated_at
      remove_column :users, :visits_count
      remove_column :users, :last_login_at
      remove_column :photos, :user_id
      execute("ALTER TABLE roles_users DROP CONSTRAINT roles_users_role_id_fkey")
      execute("ALTER TABLE roles_users DROP CONSTRAINT roles_users_user_id_fkey")
      drop_table :roles_users
      drop_table :roles
    end
  end
end
